<?php

/**
 * This is the model class for table "iteracion".
 *
 * The followings are the available columns in table 'iteracion':
 * @property integer $id
 * @property integer $idExperimento
 * @property string $bitacora
 * @property string $fechaIni
 * @property string $fechaFin
 * @property double $unidadVPaso
 *
 * The followings are the available model relations:
 * @property Fin[] $fins
 * @property Experimento $idExperimento0
 * @property Variablexiteracion[] $variablexiteracions
 */
class Iteracion extends CActiveRecord
{
	public $datos;
    
        /**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Iteracion the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'iteracion';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('idExperimento', 'required'),
			array('idExperimento', 'numerical', 'integerOnly'=>true),
			array('unidadVPaso', 'numerical'),
			array('bitacora', 'length', 'max'=>255),
			array('fechaIni, fechaFin', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, idExperimento, fechaIni, fechaFin, unidadVPaso', 'safe', 'on'=>'search'),
                        array('datos', 'file', 'types'=>'xml'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'fins' => array(self::HAS_MANY, 'Fin', 'idIteracion'),
			'idExperimento0' => array(self::BELONGS_TO, 'Experimento', 'idExperimento'),
			'variablexiteracions' => array(self::HAS_MANY, 'Variablexiteracion', 'idIteracion'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'idExperimento' => 'Experiment',
			'bitacora' => 'Notes',
			'fechaIni' => 'Initial Date',
			'fechaFin' => 'End Date',
			'unidadVPaso' => 'Chabge Value',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		//$criteria->compare('idExperimento',$this->idExperimento);
		//$criteria->compare('bitacora',$this->bitacora,true);
		$criteria->compare('fechaIni',$this->fechaIni,true);
		$criteria->compare('fechaFin',$this->fechaFin,true);
		$criteria->compare('unidadVPaso',$this->unidadVPaso);
                
                $criteria->condition='idExperimento=:experimentoId';
                $criteria->params=array(':experimentoId'=>$this->idExperimento);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
        
        public function getExperimentoText()
        {
            $experimento = Experimento::model()->findByPk($this->idExperimento);
            return $experimento->descripcion;
        }
        
        /*
        * Determines whether or not a variable of an equipo is already part of a iteracion
        */
        public function isEquipoVariableinIteracion($equipo, $variable)
        {
            $sql = "SELECT idEquipo FROM variablexiteracion WHERE idEquipo=:equipoId AND idVariable=:variableId AND idIteracion=:iteracionId";
            $command = Yii::app()->db->createCommand($sql);
            $command->bindValue(":equipoId", $equipo, PDO::PARAM_INT);
            $command->bindValue(":variableId", $variable, PDO::PARAM_INT);
            $command->bindValue(":iteracionId", $this->id, PDO::PARAM_INT);
            return $command->execute()==1;
        }
        
        public function assignEquipoVariable($equipoId, $variableId)
        {
            $command = Yii::app()->db->createCommand();
            $command->insert('variablexiteracion', array(
                        'idVariable'=>$variableId,
                        'idEquipo'=>$equipoId,
                        'idIteracion'=>$this->id,)
            );
        }
        
        /**
	 * Generates an array of equipos to use for the autocomplete
	 */
        public static function getEquipoList()
        {
            $equipoArray = CHtml::listData(Equipo::model()->findAll(), 'id', 'nombre');
            //$misequipos= $this->getEquipoVariable();
            return $equipoArray;
           /* $sql = "SELECT e.id as miid, e.nombre FROM equipo e, variablexiteracion uxp WHERE idIteracion=:iteracionId and e.id=uxp.idEquipo";
            $command = Yii::app()->db->createCommand($sql);
            $command->bindValue(":iteracionId", $this->idProyecto, PDO::PARAM_INT);
            $rows = $command->queryAll();
            $usernames = array();
		foreach($rows as $row)
		{
			$usernames[$row['miid']]=$row['nombre'];
		}
            return $usernames;*/
        }
        
	
        /**
	 * Generates an array of variables to use for the autocomplete
	 */
	public static function getVariableList()
        {
            $variableArray = CHtml::listData(Variable::model()->findAll(), 'id', 'nombre');
            return $variableArray;
        }
        
        public function getEquipoVariable()
        {
            $sql = "SELECT e.nombre, v.nombre as miv FROM equipo e, variablexiteracion vxi, variable v WHERE idIteracion=:iteracionId and e.id=idEquipo and v.id=idVariable";
            $command = Yii::app()->db->createCommand($sql);
            $command->bindValue(":iteracionId", $this->id, PDO::PARAM_INT);
            $rows = $command->queryAll();
            
           $equipo = array();
		foreach($rows as $row)
		{
			$equipo[]=$row['nombre']." --->".$row['miv'];
		}
            return $equipo;
        }
        
        //solo funciona para variables de masa y de tiempo    
        public function displayXML()
        {
            $var1=Variable::model()->findByAttributes(array('nombre'=>"masa"));
            $idmasa=$var1->id;
            
            $sql = "SELECT idVariable, valor FROM variablexiteracion WHERE  idIteracion=:iteracionId";
            $command = Yii::app()->db->createCommand($sql);
            $command->bindValue(":iteracionId", $this->id, PDO::PARAM_INT);
            $rows = $command->queryAll();
            
            $masa = array();
            $tiempo=array();
            foreach($rows as $row)
            {
                 if($idmasa == $row['idVariable'])
                 {
                     $masa[]=$row['valor'];
                 }
                 else
                 {
                     $tiempo[]=$row['valor'];
                 }
            }
            return array_combine($tiempo, $masa);
        }
}